package per.yhh.xxxtsj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import per.yhh.xxxtsj.entity.Good;
import per.yhh.xxxtsj.entity.Myorder;
import per.yhh.xxxtsj.entity.PageResult;
import per.yhh.xxxtsj.entity.User;
import per.yhh.xxxtsj.mapper.MyorderMapper;
import per.yhh.xxxtsj.service.MyorderService;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yhh
 * @since 2022-04-17
 */
@Service
public class MyorderServiceImpl extends ServiceImpl<MyorderMapper, Myorder> implements MyorderService {

    @Autowired
    MyorderMapper myorderMapper;

    @Override
    public Myorder buy(User user, Good good) {
        Myorder myorder = new Myorder();
        myorder.setUid(user.getUid());
        myorder.setGid(good.getGid());
        myorder.setOrderStatus(0);
        myorderMapper.insert(myorder);
        myorder.setOid(Long.valueOf(myorderMapper.getLastInsertId()));
        return myorder;
    }

    @Override
    public PageResult<Myorder> getOrderByPageAndKeyAndId(Long uid, String keyword, Integer pageNum, Integer pageSize) {
        pageSize = Math.min(pageSize, 10);
        pageNum = Math.max(pageNum, 1);
        Page<Myorder> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Myorder> queryWrapper = new QueryWrapper<Myorder>();
        queryWrapper.eq("uid",uid);
        if (!Objects.equals(keyword, "")) {
            queryWrapper.like("note", keyword)
                    .or()
                    .eq("gid", keyword);
        }
        Page<Myorder> m = myorderMapper.selectPage(page, queryWrapper);
        return new PageResult<>(m.getRecords(), m.getPages());
    }

    @Override
    public PageResult<Myorder> getOrderByPage(String keyword, Integer pageNum, Integer pageSize) {
        pageSize = Math.min(pageSize, 10);
        pageNum = Math.max(pageNum, 1);
        Page<Myorder> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Myorder> queryWrapper = null;
        if (!Objects.equals(keyword, "")) {
            queryWrapper = new QueryWrapper<Myorder>();
            queryWrapper.like("note", keyword)
                    .or()
                    .eq("uid", keyword)
                    .or()
                    .eq("gid", keyword);
        }
        Page<Myorder> m = myorderMapper.selectPage(page, queryWrapper);
        return new PageResult<>(m.getRecords(), m.getPages());
    }
}
